﻿using Yxinmt.Interface;
using System.Collections.Generic;
using Yxinmt.Controls;
using System;
using Yxinmt.Utility;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using System.Windows;
using System.IO;
using System.Windows.Interop;
using System.Reflection;
using Yxinmt.Entity;
using System.Windows.Input;
using System.Xml.Linq;
using Yxinmt.SmarterStreaming;

namespace Yxinmt.Windows.Meeting
{
    public class Index : BaseWindow, IWindow
    {
        public Entity.ClientConfig ClientConfig { get; set; }

        public Index(Window window, Dictionary<string, object> parameters, Entity.ClientConfig clientConfig, MainWindow win)
        {
            Window = window;
            _Parameters = parameters;
            InitSet(string.Empty);
            ClientConfig = clientConfig;

            initView();

            win.ExitAction = () => SetExit();

            this.SetWindow();

            initLoad();
        }

        string _Url { get; set; }
        void initView()
        {
        
            if (!string.IsNullOrEmpty(ClientConfig.ServiceUrl))
            {
                long time = 0;
                int count = 0;

                do
                {
                    time = RequestService.GetCurrentTime(ClientConfig.ServiceUrl);
                    if (time == 0)
                    {
                        Thread.Sleep(3000);
                        count++;
                    }
                }
                while (time == 0 && count < 3);

                if (time == 0) ClientConfig.ServiceUrl = string.Empty;
            }

            string theme = AppSetting.Theme;
            if (!string.IsNullOrEmpty(theme)) SetTheme(theme);

            //string id = "e8cc559e-8d11-4613-9b95-3e7ee97ca037";
            //Guid meetingId = new Guid("2c1ef632-ff28-11ef-a5e4-fa163e8ce498");
            //_Url = $"http://192.168.0.105:8080/preview.html?id={id}&sid={_ClientConfig.Serial}&MeetingId={meetingId}";

            //_Url = "http://localhost:8080/preview.html?id=f8a565e7-46c6-4f10-bd67-4e4ac3500281&_rTkdcWYZYkw=0.9961083921943239&MeetingId=19643fa7-211d-960f-dc7c-47856db9393c";

            var v = string.IsNullOrEmpty(ClientConfig.ServiceUrl);
            if (!v) setGetUserInfoResponse();
            v = UserInfo == null;
            var grid1 = Utility.Common.GetProperty(_View, "Grid1");
            grid1["Visible"] = v;
            var grid2 = Utility.Common.GetProperty(_View, "Grid2");
            grid2["Visible"] = !v;
            if (!v)
            {
                string pageName = "index";
                if (UserInfo.DeviceType == 2) pageName = "serviceList";
                else if (UserInfo.DeviceType == 3) pageName = "bigScreen";

                _Url = GetWebUrl(pageName);

                var webView2 = Utility.Common.GetProperty(_View, "WebView2");
                webView2["Url"] = _Url;
            }
        }

        public string GetWebUrl(string pageName)
        {
            return $"{ClientConfig.ServiceUrl}/{pageName}.html?sid={ClientConfig.Serial}&_rd={new Random().NextDouble()}";
        }

        IControl serviceUrlTextBox { get; set; }
        ComboBox meetingRoomComboBox { get; set; }
        ComboBox dispalyIndexComboBox { get; set; }

        IControl deviceTypeComboBox { get; set; }
        ImageTextButton saveButton { get; set; }

        ImageTextButton shareTextButton { get; set; }

        IComponent _Grid1 { get; set; }
        IComponent _Grid2 { get; set; }
        IComponent _Grid3 { get; set; }
        Popup _Popup1 { get; set; }

        Popup _Popup2 { get; set; }

        Image _img_loading { get; set; }

        WebView2 _WebView2 { get; set; }

        IComponent _DockPanel2 { get; set; }
        IComponent _DockPanel3 { get; set; }

        void initLoad()
        {
            serviceUrlTextBox = GetControl("ServiceUrl");
            meetingRoomComboBox = (ComboBox)GetControl("MeetingRoomId");
            meetingRoomComboBox.SelectionChanged = meetingRoomChanged;
            dispalyIndexComboBox = (ComboBox)GetControl("DisplayIndex");
            deviceTypeComboBox = GetControl("DeviceType");
            shareTextButton = (ImageTextButton)GetControl("shareTextButton");
            saveButton = (ImageTextButton)GetControl("Save");
            _WebView2 = (WebView2)GetControl("WebView2");
            _Grid1 = GetComponent("Grid1");
            _Grid2 = GetComponent("Grid2");
            _Grid3 = GetComponent("Grid3");
            _Popup1 = (Popup)GetControl("Popup1");
            _Popup2 = (Popup)GetControl("Popup2");
            _Popup2.OnClick = () => this.ShowDocumentView();
            _img_loading = (Image)GetControl("img_loading");

            _DockPanel2 = GetComponent("DockPanel2");
            _DockPanel3 = GetComponent("DockPanel3");

            _WebView2.ReceiveMessage = (msg) =>
            {
                try
                {
                    var type = msg.GetStringValue("type");
                    var data = msg.GetValue<Dictionary<string, object>>("data");
                    if (type == "closeWin") Window.Close();
                    else if (type == "setMinWin") this.SetFormWindowState("Minimized");
                    else if (type == "startShare") StartShare(data);
                    else if (type == "endShare") EndShare();
                    else if (type == "receiveStartShare") ReceiveStartShare(data);
                    else if (type == "receiveEndShare") receiveEndShare(true);
                    else if (type == "importTemplate") importTemplate();
                    else if (type == "downloadTemplate") downloadTemplate();
                    else if (type == "importUsers") importUsers();
                    else if (type == "exportUsers") exportUsers(data);
                    else if (type == "exportVotes") exportVotes(data);
                    else if (type == "exportScores") exportScores(data);
                    else if (type == "exportVoteResult") exportVoteResult(data);
                    else if (type == "exportScoreResult") exportScoreResult(data);
                    else if (type == "exportUserSigns") exportUserSigns(data);
                    else if (type == "setReceSharingData") UserInfo.ReceSharingData = data;
                    else if (type == "openFile") openFile(data);
                    else if (type == "closeFile") closeFile(data);
                    else if (type == "lockScreen") lockScreen(data);
                    else if (type == "toWhiteboard") toWhiteboard(data);
                    else if (type == "toMeetingRecord") toMeetingRecord(data);
                    else if (type == "openVideoPlay") openVideoPlay(data);
                    else if (type == "sysncFullScreen") sysncFullScreen(data);
                    else if (type == "videoToBack") videoToBack();
                    else if (type == "uploadFiles") uploadFiles();
                    else if (type == "uploadDirFiles") uploadDirFiles();
                    else if (type == "startUpload") startUpload(data);
                    else if (type == "closeUpload") closeUpload();
                    else if (type == "downloadFiles") downloadFiles(data);
                    else if (type == "setUserName") setUserName(data);
                    else if (type == "toSetSystem") toSetSystem();
                    else if (type == "changeMeetingRoom") changeMeetingRoom(data);
                    else if (type == "receiveService") receiveService(data);
                    else if (type == "resetMeeting") resetMeeting(data);
                    else if (type == "adjournMeeting") adjournMeeting(data);
                    else if (type == "updateDeviceRole") updateDeviceRole(data);
                    else if (type == "sendMeetingNotice") sendMeetingNotice(data);
                    else if (type == "syncBigScreen") syncBigScreen(data);
                    else if (type == "closeMeetingNotice") closeMeetingNotice();
                    else if (type == "exitMeeting") exitMeeting();
                    else if (type == "endMeeting") endMeeting();
                    else if (type == "changePage") changePage();
                    else if (type == "closeBigScreen") closeBigScreen();
                    else if (type == "changeService") changeService();
                    else if (type == "getShareText") getShareText();
                    else if (type == "toMeetingShare") toMeetingShare(data);
                }
                catch (Exception ex)
                {
                    Alert(ex.Message);
                    Utility.LoggerProxy.Exception("WebView2", "ReceiveMessage", ex);
                }
            };

            setFilterResponse();

            InitStreaming();

            Utils.SetLoadingAnimation(_img_loading.GetImage());
        }

        void getShareText()
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data["IsPublish"] = IsPublish;

            _WebView2.Send("setShareText", data);
        }
        System.Windows.Window _MeetingNotice { get; set; }
        System.Windows.Controls.Grid _MeetingNoticeGrid { get; set; }
        System.Windows.Controls.TextBlock _MeetingNoticeTextBlock { get; set; }

        public void UpdateDevice(Guid deviceId, int displayIndex, byte isPresident)
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data["DisplayIndex"] = displayIndex;
            data["IsPresident"] = isPresident;
            data["UserId"] = deviceId;

            if (deviceId == UserInfo.UserId)
            {
                if (UserInfo.DisplayIndex != displayIndex || UserInfo.IsPresident != isPresident)
                {
                    UserInfo.DisplayIndex = displayIndex;
                    UserInfo.IsPresident = isPresident;
                }
                else return;

                _WebView2.Send("updateDeviceRole", data);
            }
        }

        string _ServiceUrl { get; set; }

        void toMeetingShare(Dictionary<string,object> data)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var url = GetWebUrl("shareScreen");
            parameters["Url"] = url + "&MeetingId=" + data.GetStringValue("MeetingId");
            parameters["Index"] = this;
            var mainWindow = new MainWindow(GetNewWindow(), "WebPage", this, parameters);
            mainWindow.ShowDialog();
        }

        void changeService() {
            _Grid2.SetVisible(false);
            _Grid1.SetVisible(true);
            _DockPanel3.SetVisible(false);
            _ServiceUrl = ClientConfig.ServiceUrl.Replace("http://", string.Empty).Replace("/", string.Empty);
            serviceUrlTextBox.SetValue(_ServiceUrl);  
            _DockPanel2.SetVisible(true);
        }

        void exitMeeting() {
            if (_Popup2.IsOpen) _Popup2.Hide();
        }

        void closeBigScreen()
        {
            if (!_IsBigScreen) return;
            this.closeMeetingNotice();
        }

        void endMeeting()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var url = GetWebUrl("endMeetingTip");
            parameters["Url"] = url;
            parameters["Index"] = this;
            var mainWindow = new MainWindow(GetNewWindow(), "WebPage", this, parameters);
            mainWindow.ShowDialog(() =>
            {
                if (_Popup2.IsOpen) _Popup2.Hide();
                if (_DocumentViewing != null)
                {
                    _DocumentViewing.AllCloseTab(null);
                    _DocumentViewing = null;
                    this._Grid2.SetVisible(true);
                }
                this._WebView2.Send("endMeeting", new Dictionary<string, object>());
            });
        }

        void changePage()
        {
            if (_DocumentViewing != null)
            {
                _DocumentViewing.AllCloseTab(null);
                _DocumentViewing = null;
                this._Grid2.SetVisible(true);
            }
            if(_VideoPlay!= null)
            {
                _VideoPlay.RevceToBack();
                _VideoPlay = null;
            }
            exitMeeting();
        }

        void closeMeetingNotice()
        {
            if (_MeetingNotice != null) _MeetingNotice.Close();

        }

        void syncBigScreen(Dictionary<string, object> data)
        {
            data["IsBigScreen"] = true;
            sendMeetingNotice(data);
        }

        bool _IsBigScreen { get; set; }

        void sendMeetingNotice(Dictionary<string, object> data)
        {
            var isBigScreen = data.GetValue<bool>("IsBigScreen");
            this._IsBigScreen = isBigScreen;
            if (_MeetingNotice == null)
            {
                _MeetingNotice = GetNewWindow();
                var grid = new System.Windows.Controls.Grid();
                grid.Width = 320;
                grid.Height = 180;

                var textBlock = new System.Windows.Controls.TextBlock();
            
                textBlock.TextWrapping = System.Windows.TextWrapping.Wrap;
                textBlock.FontSize = 18;
                textBlock.LineHeight = 27;
                textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                textBlock.Padding = new System.Windows.Thickness(16);

                grid.Children.Add(textBlock);

                MethodInfo m = _MeetingNotice.GetType().GetMethod("AddChildControl");
                if (m != null) m.Invoke(_MeetingNotice, new object[] { grid });

                _MeetingNotice.Width = grid.Width;
                _MeetingNotice.Height = grid.Height;
                _MeetingNotice.Top = 0;
                _MeetingNotice.Left = 0;
                _MeetingNotice.WindowStyle = WindowStyle.SingleBorderWindow;
                _MeetingNotice.ResizeMode = ResizeMode.NoResize;

                _MeetingNotice.Title = isBigScreen ? "欢迎您" : "会议公告";

                _MeetingNoticeGrid = grid;
                _MeetingNoticeTextBlock = textBlock;
                setBackImageContentColor(data, isBigScreen, _MeetingNoticeGrid, _MeetingNoticeTextBlock);

                _MeetingNotice.Closed += _MeetingNotice_Closed;
                _MeetingNotice.Show();

                if (textBlock.ActualHeight + 24 > grid.Height)
                {
                    grid.Height = textBlock.ActualHeight + 24;
                    _MeetingNotice.Height = grid.Height;
                }
            }
            else
            {
                setBackImageContentColor(data, isBigScreen, _MeetingNoticeGrid, _MeetingNoticeTextBlock);
            }
        }

        private void _MeetingNotice_Closed(object sender, EventArgs e)
        {
            _MeetingNotice = null;
        }

        void setBackImageContentColor(Dictionary<string, object> data, bool isBigScreen, System.Windows.Controls.Grid grid, System.Windows.Controls.TextBlock textBlock)
        {
            textBlock.Text = data.GetStringValue("Content");
            var backImageUrl = data.GetStringValue("BackImageUrl");
            if (!string.IsNullOrEmpty(backImageUrl))
            {
                backImageUrl = ClientConfig.ServiceUrl + backImageUrl;
                this.SetBackgroundImage(_MeetingNotice, backImageUrl, string.Empty);
            }
            else grid.Background = null;

            var fontColor = data.GetStringValue("FontColor");
            if (string.IsNullOrEmpty(fontColor)) fontColor = "#000000";

            textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Utility.Common.GetColor(fontColor));

            var displayMethod = data.GetValue<int>("DisplayMethod");
            _MeetingNotice.WindowState = displayMethod == 1 || isBigScreen ? WindowState.Maximized : WindowState.Normal;
            _MeetingNoticeTextBlock.FontSize = displayMethod == 1 || isBigScreen ? 14 : 18;
            _MeetingNoticeTextBlock.LineHeight = _MeetingNoticeTextBlock.FontSize * 1.5;
        }

        void updateDeviceRole(Dictionary<string, object> data)
        {
            UserInfo.IsPresident = data.GetValue<byte>("IsPresident");
            if (data.ContainsKey("DisplayIndex")) UserInfo.DisplayIndex = data.GetValue<int>("DisplayIndex");
        }

        WebPage _AdjournMeeting { get; set; }

        void adjournMeeting(Dictionary<string, object> data)
        {
            var meetingId = data.GetValue<Guid>("MeetingId");
            var adjournType = data.GetValue<int>("AdjournType");
            if (adjournType == 2)
            {
                if (_AdjournMeeting != null)
                {
                    _AdjournMeeting.Window.DialogResult = false;
                    _AdjournMeeting = null;
                }
                return;
            }

            if (_AdjournMeeting != null) return;

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var url = GetWebUrl("adjournMeeting");
            parameters["Url"] = url + "&MeetingId=" + data.GetStringValue("MeetingId");
            parameters["Index"] = this;
            var mainWindow = new MainWindow(GetNewWindow(), "WebPage", this, parameters);
            _AdjournMeeting = (WebPage)mainWindow.CurrentWindow;
            mainWindow.ShowDialog();
        }

        void resetMeeting(Dictionary<string,object> data)
        {
            var meetingId = data.GetValue<Guid>("MeetingId");
            string path = AppDomain.CurrentDomain.BaseDirectory+"res\\"+ meetingId;
            if (Directory.Exists(path))
            {
                var list = Directory.GetFiles(path);

                foreach (var file in list)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                    }
                }
            }
        }

        void receiveService(Dictionary<string, object> data)
        {
            var createUser = data.GetValue<Guid>("CreateUser");
            if (createUser == UserInfo.UserId)
            {
                this.Alert("服务请求已收到，请稍等");
            }
        }

        void changeMeetingRoom(Dictionary<string, object> data)
        {
            UserInfo.MeetingRoomId = data.GetStringValue("MeetingRoomId");
            UserInfo.DisplayIndex = data.GetValue<int>("DisplayIndex");

            _WebView2.Send("changeMeetingRoom", new Dictionary<string, object>());
        }

        void toSetSystem()
        {
            if (AppSetting.IsToAdmin == "false") return;
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["Url"] = $"{ClientConfig.ServiceUrl}/admin/deviceList.html?isclient=true";
            parameters["Index"] = this;
            var mainWindow = new MainWindow(GetNewWindow(), "WebAdminPage", this, parameters);
            mainWindow.Window.Show();
        }

        void setUserName(Dictionary<string, object> data)
        {
            if (_SecondIndex == null) return;
            string name = data.GetStringValue("Name");
            if (string.IsNullOrEmpty(name) || name== "匿名" || name == "参与者") name = "参与者";

            _SecondIndex.SetLabel(name);
        }

        SecondIndex _SecondIndex { get; set; }

        void loadSecondWindow(Dictionary<string, object> parameters)
        {
            if(UserInfo!=null)parameters["Theme"] = UserInfo.Theme;
            var screens = System.Windows.Forms.Screen.AllScreens;

            // 副窗口显示在副屏幕
            if (screens.Length > 1)
            {
                var secondScreen = screens.Where(w => !w.Primary).FirstOrDefault();
                if (secondScreen == null) return;

                var mainWindow = new MainWindow(GetNewWindow(), "SecondIndex", this, parameters);
                var window = mainWindow.Window;
                _SecondIndex = mainWindow.CurrentWindow as SecondIndex;
                window.WindowStyle = System.Windows.WindowStyle.None;
                window.ResizeMode = System.Windows.ResizeMode.NoResize;
                window.Show();

                var handle = new WindowInteropHelper(window).Handle;
                Utility.Win32Api.SetWindowPos(handle, IntPtr.Zero, secondScreen.Bounds.Left, secondScreen.Bounds.Top, secondScreen.Bounds.Width, secondScreen.Bounds.Height, 0x0040);
            }
        }

        public override void DataLoad()
        {
            base.DataLoad();

            if (UserInfo != null && UserInfo.DeviceType == 1)
            {
                var parameters = new Dictionary<string, object>();
                parameters["Name"] = "参与者";
                loadSecondWindow(parameters);
            }

            UploadDownload.ServiceUrl= ClientConfig.ServiceUrl;
            UploadDownload.DownloadProgress = (file) =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        Window.Dispatcher.Invoke(() =>
                        {
                            var data = new Dictionary<string, object>();
                            data["Files"] = new List<Entity.FileInfo>() { file };
                            _WebView2.Send("downloadProgress", data);
                        });
                    }
                    catch
                    {

                    }
                });
            };
        }

        void downloadFiles(Dictionary<string,object> data)
        {
            var files = Utility.Common.DictionaryListToList<Entity.FileInfo>(data.GetValue < List<Dictionary<string, object>>>("Files"));
            var meetingId = data.GetValue<Guid>("MeetingId");

            files = UploadDownload.DownloadFileList(meetingId, UserInfo.VideoFormatList, files);

            if (files.Count > 0)
            {
                data = new Dictionary<string, object>();
                data["Files"] = files;
                _WebView2.Send("downloadProgress", data);
            }
        }


        UploadDownload _UploadDownload { get; set; }

        void closeUpload()
        {
            if (_UploadDownload != null)
            {
                _UploadDownload.CancelUpload();
                _UploadDownload = null;
            }
        }

        void startUpload(Dictionary<string, object> data)
        {
            var files = Utility.Common.DictionaryListToList<Entity.UploadFile>(data.GetValue<List<Dictionary<string, object>>>("Files"));

            //FileId, TotalUploadStatus, UploadPercent

            Guid meetingId = data.GetValue<Guid>("MeetingId");

            _UploadDownload = new UploadDownload();
            _UploadDownload.ProgressCallback = (bytesSent,e,p, file) =>
            {
                Task.Run(() =>
                {
                    Window.Dispatcher.Invoke(() =>
                    {
                        Dictionary<string, object> dict = new Dictionary<string, object>();
                        dict["FileId"] = file.FileId;
                        if (!string.IsNullOrEmpty(file.Message)) dict["Message"] = "上传失败：" + file.Message;
                        dict["UploadPercent"] = p;
                        dict["TotalUploadStatus"] = getTotalUploadStatus(bytesSent, file, files, e);

                        _WebView2.Send("uploadProgress", dict);
                    });
                });
            };
            _UploadDownload.Upload(meetingId, files, (elapsed) =>
            {
                Task.Run(() =>
                {
                    Thread.Sleep(100);
                    Window.Dispatcher.Invoke(() =>
                    {
                        Dictionary<string, object> dict2 = new Dictionary<string, object>();
                        dict2["TotalUploadStatus"] = getTotalUploadStatus(0, null, files, elapsed);
                        dict2["Files"] = files.Where(s => s.IsComplete).ToList();
                        _WebView2.Send("uploadProgress", dict2);
                    });
                });
            });
            
        }

        string getTotalUploadStatus(long bytesSent, Entity.UploadFile file, List<Entity.UploadFile> files, long elapsed)
        {
            //上传大小：40.46 MB共耗时：15.01秒平均上传速度：2.70 MB/s上传成功：3个
            //总进度：93.06%正在上传：(1/4)上传速度：2.90 MB/s预计耗时：2.224秒

            long totalSize = 0;
            int succeedCount = 0;
            int failedCount = 0;
            long uploadSize = 0;
            files.ForEach(f =>
            {
                if (file != null && file.FileId != f.FileId && f.IsComplete) uploadSize += f.FileSize;
                totalSize += f.FileSize;
                if (string.IsNullOrEmpty(f.Message)) succeedCount++;
                else failedCount++;
            });

            string totalSizeText = Utility.Common.GetFileSize(totalSize);
            var seconds = Math.Round(elapsed / 1000.00, 2);

            if (file == null)
            {
                string msg = string.Empty;
                if (succeedCount > 0) msg += $"，上传成功：{succeedCount}个";
                if (failedCount > 0) msg += $"，上传失败：{failedCount}个";
                var seed = Utility.Common.GetFileSize(totalSize * 1000 / elapsed) + "/s";
                return $"上传大小：{totalSizeText}，共耗时：{seconds}秒，平均上传速度：{seed}{msg}";
            }
            else
            {
                var rate = Math.Round((uploadSize + bytesSent) * 100 / (totalSize * 1.00), 2);
                var seed = Utility.Common.GetFileSize(bytesSent * 1000 / elapsed) + "/s";
                double orderTime = elapsed;
                if (bytesSent > 0 && elapsed > 0) orderTime += (double)(file.FileSize - bytesSent) * 1.00 / (bytesSent * 1.00 / elapsed * 1.00);
                var elapsed2 = Math.Round(orderTime / 1000, 2);
                return $"总进度：{rate}%，正在上传：（{file.Index}/{files.Count}），上传速度：{seed}，预计耗时：{elapsed2}秒";
            }
        }

        void uploadFiles()
        {
            using (System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog())
            {
                dialog.Multiselect = true;
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        List<Entity.UploadFile> uploadFiles = new List<Entity.UploadFile>();
                        getUploadFiles(uploadFiles, dialog.FileNames, "/");

                        Dictionary<string, object> data = new Dictionary<string, object>();
                        data["Files"] = uploadFiles;
                        if (uploadFiles.Count == 0)
                        {
                            alertNoFile();
                            return;
                        }

                        _WebView2.Send("uploadFiles", data);
                    }
                    catch (Exception ex)
                    {
                        Alert(ex.Message);
                    }
                }
            }
        }

        void alertNoFile()
        {
            Alert("未有符合格式的文件");
        }

        void getUploadFiles(List<Entity.UploadFile> list, string[] fileNames, string dirNames)
        {
            Entity.UploadFile file = null;
            for (int i = 0; i < fileNames.Length; i++)
            {
                var fileInfo = new System.IO.FileInfo(fileNames[i]);

                file = new Entity.UploadFile();
                file.UploadStatus = "等待上传";
                file.DirFileName = dirNames + fileInfo.Name;
                file.FileName = fileInfo.Name;
                file.FilePath = fileInfo.FullName;
                file.FileSize = fileInfo.Length;
                file.DirNames = dirNames;
                file.FileType = System.IO.Path.GetExtension(fileInfo.FullName);
                file.FileSizeText = Utility.Common.GetFileSize(fileInfo.Length);

                if (UserInfo.FileFormatList.Contains(file.FileType)) list.Add(file);

                if (list.Count > 50)
                {
                    throw new Exception("选择上传的文件数不能超过50个！");
                }
            }
        }

        void uploadDirFiles()
        {
            using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择一个文件夹";
                System.Windows.Forms.DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog.SelectedPath);

                        if (directoryInfo.GetFiles().Count() == 0)
                        {
                            Alert("对不起，请选择有文件的文件夹");
                            return;
                        }

                        List<Entity.UploadFile> uploadFiles = new List<Entity.UploadFile>();
                        getDirectoryFiles(uploadFiles, directoryInfo, "/", 1);

                        Dictionary<string, object> data = new Dictionary<string, object>();
                        data["Files"] = uploadFiles;

                        if (uploadFiles.Count == 0)
                        {
                            alertNoFile();
                            return;
                        }

                        _WebView2.Send("uploadFiles", data);
                    }
                    catch (Exception ex)
                    {
                        Alert(ex.Message);
                    }
                }
            }
        }

        void getDirectoryFiles(List<Entity.UploadFile> uploadFiles, DirectoryInfo dir, string dirNames, int dirCount)
        {
            var files = dir.GetFiles();

            if (files.Length > 0 && dirCount > 5)
            {
                throw new Exception("选择上传的文件夹层级不能超过5层！");
            }

            getUploadFiles(uploadFiles, files.Select(s => s.FullName).ToArray(), dirNames);

            var dirs = dir.GetDirectories();
            if (files.Length == 0 && dirs.Length == 0)
            {
                throw new Exception($"{dirNames.TrimEnd('/')}为空目录");
            }
            if (dirs.Length > 0)
            {
                dirNames += dir.Name + "/";
                dirCount++;

                foreach (var d in dirs)
                {
                    getDirectoryFiles(uploadFiles, d, dirNames, dirCount);
                }
            }
        }

        void toWhiteboard(Dictionary<string, object> data)
        {
            Guid meetingId = data.GetValue<Guid>("MeetingId");
            Entity.FileInfo file = new Entity.FileInfo();
            file.FileId = Guid.NewGuid();
            file.FileType = ".png";
            file.FileName = "新建白板1.png";
            file.RecordType = 2;

            saveRecord(file, meetingId);

            showDocumentViewing(meetingId, file);
        }

        void toMeetingRecord(Dictionary<string, object> data)
        {
            Guid meetingId = data.GetValue<Guid>("MeetingId");
            Entity.FileInfo file = new Entity.FileInfo();
            file.FileId = Guid.NewGuid();
            file.FileType = ".pdf";
            file.FileName = "新建笔记1.pdf";
            file.RecordType = 3;
            file.IsNew = true;

            saveRecord(file, meetingId);

            showDocumentViewing(meetingId, file);
        }

        void saveRecord(Entity.FileInfo file, Guid meetingId)
        {
            TaskRun("saveRecord", true, () =>
            {
                var record = new Dictionary<string, object>();

                record["RecordId"] = file.FileId;
                record["FileName"] = file.FileName;
                record["RecordType"] = file.RecordType;
                record["MeetingId"] = meetingId;
                record["FileType"] = file.FileType;

                var res = RequestService.SaveRecord(record, false);
                if (!res.Result) Alert(res.Message);
            });
        }

        void lockScreen(Dictionary<string, object> data)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var url = GetWebUrl("lockScreen");
            parameters["Url"] = url + "&MeetingId=" + data.GetStringValue("MeetingId");
            parameters["Index"] = this;
            var mainWindow = new MainWindow(GetNewWindow(), "WebPage", this, parameters);
            mainWindow.ShowDialog();
        }

        void closeFile(Dictionary<string, object> data)
        {
            Guid meetingId = data.GetValue<Guid>("MeetingId");
            Entity.FileInfo file = Utility.Common.DictionaryTo<Entity.FileInfo>(data);
            if (UserInfo.VideoFormatList.Contains(file.FileType) || file.VideoType == 2)
            {
                if (_VideoPlay != null)
                {
                    if (_VideoPlay.RevceToBack(file))
                    {
                        _VideoPlay = null;
                    }
                }
            }
            else
            {
                if (UserInfo.DeviceType == 3) return;
                if (_DocumentViewing != null && _DocumentViewing.MeetingId == meetingId)
                {
                    _DocumentViewing.CloseTabByFileId(file.FileId);
                    if (_DocumentViewing.TabList.Count == 0)
                    {
                        _DocumentViewing = null;
                        exitMeeting();
                        this._Grid2.SetVisible(true);
                    }
                }
            }
        }

        void sysncFullScreen(Dictionary<string, object> data)
        {
            if(UserInfo.DeviceType == 3) return;
            if (_VideoPlay != null) _VideoPlay.SynscFullScreen2(data);
        }

        void videoToBack()
        {
            if (_VideoPlay != null)
            {
                _VideoPlay.RevceToBack();
                _VideoPlay = null;
            }
        }


        void openFile(Dictionary<string, object> data)
        {
            Guid meetingId = data.GetValue<Guid>("MeetingId");
            bool isHost = data.GetValue<bool>("IsHost");
            Entity.FileInfo file = Utility.Common.DictionaryTo<Entity.FileInfo>(data);
            if (UserInfo.VideoFormatList.Contains(file.FileType) || file.VideoType == 2) showVideoPlay(meetingId, isHost, file);
            else
            {
                if (UserInfo.DeviceType == 3) return;
                if (_VideoPlay != null)
                {
                    _VideoPlay.ToBack(null);
                }
                showDocumentViewing(meetingId, file);
            }
        }

        void openVideoPlay(Dictionary<string, object> data)
        {
            Guid meetingId = data.GetValue<Guid>("MeetingId");
            bool isHost = data.GetValue<bool>("IsHost");
            showVideoPlay(meetingId, isHost, null);
        }

        DocumentViewing _DocumentViewing { get; set; }

        void showDocumentViewing(Guid meetingId, Entity.FileInfo file)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["MeetingId"] = meetingId;
            parameters["File"] = file;

            if (_DocumentViewing != null && _DocumentViewing.MeetingId != meetingId)
            {
                _DocumentViewing.AllCloseTab(null);
                _DocumentViewing = null;
            }

            if (_DocumentViewing == null)
            {
                _DocumentViewing = new DocumentViewing(this.Window, this, Grid, parameters);
                _DocumentViewing.GridPageLoad();
                _Grid2.SetVisible(false);
            }
            else
            {
                _DocumentViewing.AddTab(file);
                _Grid2.SetVisible(false);
                _DocumentViewing.Grid.Visibility = Visibility.Visible;
            }

            if (_Popup2.IsOpen) _Popup2.Hide();
        }

        void showVideoPlay(Guid meetingId, bool isHost, Entity.FileInfo file)
        {
            if (_Popup2.IsOpen) _Popup2.Hide();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["MeetingId"] = meetingId;
            parameters["IsHost"] = isHost;
            if (file != null)
            {
                if (file.VideoType == 0) file.VideoType = 1;
                parameters["File"] = file;
            }
            if (_VideoPlay != null)
            {
                if (meetingId != _VideoPlay.MeetingId)
                {
                    _VideoPlay.RevceToBack();
                    _VideoPlay = null;
                }
            }
            if (_VideoPlay != null)
            {
                _VideoPlay.PlayVideo2(isHost, file);
            }
            else
            {
                _VideoPlay = new VideoPlay(this.Window, this, Grid, parameters);
                _VideoPlay.GridPageLoad();
                _Grid2.SetVisible(false);
            }
        }

        void meetingRoomChanged(object selectItem)
        {
            List<ValueText> values = new List<ValueText>();
            string value = string.Empty;
            if (selectItem is Entity.MeetingRoom meetingRoom)
            {
                for (int i = 1; i <= meetingRoom.SeatCount; i++)
                {
                    string t = i.ToString();
                    var device = meetingRoom.Devices.Where(w => w.DisplayIndex == i).FirstOrDefault();
                    if (device == null) values.Add(new ValueText(t, t));
                    else if (device.SerialId == Utility.Common.FromBase64String(ClientConfig.Serial))
                    {
                        values.Add(new ValueText(t, t));
                        value = t;
                    }
                }
            }
            dispalyIndexComboBox.SetDateSource(values);
            dispalyIndexComboBox.SetValue(value);
        }

        public void NextStep(IControl ctl)
        {
            if (isLoading) return;

            var serviceUrl = (string)serviceUrlTextBox.GetValue();

            if (!judgeNullable(serviceUrl, "请输入服务地址")) return;

            if(_ServiceUrl == serviceUrl)
            {
                _Grid1.SetVisible(false);
                _Grid2.SetVisible(true);
                _ServiceUrl = string.Empty;
                return;
            }

            isLoading = true;

            var time = RequestService.GetCurrentTime(serviceUrl);
            if (time == 0)
            {
                Alert("服务地址不能访问！");
                isLoading = false;
                return;
            }

            try
            {
                var meetingRoomList = RequestService.GetMeetingRoomList();
                ((ComboBox)meetingRoomComboBox).SetDateSource(meetingRoomList);
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
                isLoading = false;
                return;
            }

            _DockPanel2.SetVisible(false);
            _DockPanel3.SetVisible(true);
            isLoading = false;
        }

        void importUsers()
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.DefaultExt = "xlsx";
            dialog.Filter = "Excel|*.xlsx";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    using (var fileStream = System.IO.File.OpenRead(dialog.FileName))
                    {
                        var dictList = ExcelUtility.Excel2007Import(fileStream);

                        string validateColumn(List<string> list)
                        {
                            return this.validateColumn(list);
                        }

                        string validateData(Dictionary<string, object> dict)
                        {
                            return this.validateData(dict);
                        }

                        List<Dictionary<string, object>> dataList = ExcelUtility.Excel2007Import(fileStream, validateColumn, validateData, 100);

                        if (dataList.Count == 0)
                        {
                            Alert("对不起，未有相应数据！");
                            return;
                        }

                        List<Dictionary<string, object>> userList = new List<Dictionary<string, object>>();
                        for (int i = 0; i < dataList.Count; i++)
                        {
                            Dictionary<string, object> user = new Dictionary<string, object>();
                            var data = dataList[i];
                            string deviceRole = data.GetStringValue("设备角色");
                            if (deviceRole != "参与者" && deviceRole != "主席")
                            {
                                Alert("设备角色值应为参与者或主席！");
                                return;
                            }
                            user["DisplayIndex"] = i + 1;
                            user["UserName"] = data.GetStringValue("姓名");
                            user["DeviceRole"] = deviceRole;
                            userList.Add(user);
                        }

                        Dictionary<string, object> d = new Dictionary<string, object>();
                        d["Users"] = userList;
                        _WebView2.Send("importUsers", d);
                    }
                }
                catch (Exception ex)
                {
                    Alert(ex.Message);
                    Utility.LoggerProxy.Exception("Index", "importUsers", ex);
                }
            }
        }
        private string validateColumn(List<string> list)
        {
            List<string> nameList = null;
            string message = string.Empty;

            message += "导入格式：第一行为列名，数据从第二行开始；列名需与提示的列名一致，字母区分大小写。";

            string labelNames = "姓名,设备角色";
            if (!string.IsNullOrEmpty(labelNames))
            {
                nameList = labelNames.Split(',').ToList();
                message += "列名集合：" + labelNames;
            }

            if (nameList == null) return "请设置导入所需的字段列名";

            int iCount = (from a in list
                          from b in nameList
                          where a == b
                          select a).Count();

            if (iCount != nameList.Count) return message;

            return string.Empty;
        }

        private string validateData(Dictionary<string, object> dict)
        {
            List<string> nameList = null;
            string message = string.Empty;

            string requireLabelNames = "姓名,设备角色";
            if (!string.IsNullOrEmpty(requireLabelNames))
            {
                nameList = requireLabelNames.Split(',').ToList();
                message += "字段集合：" + requireLabelNames + "，不能为空";
            }
            if (nameList == null) return string.Empty;

            bool blSucceed = true;

            foreach (string name in nameList)
            {
                if (!dict.ContainsKey(name) || dict[name] == null || string.IsNullOrEmpty(dict[name].ToString())) { blSucceed = false; break; }
            }

            if (!blSucceed) return message;

            return string.Empty;
        }

        void exportUserSigns(Dictionary<string, object> data)
        {
            if (data.ContainsKey("UserSigns"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("UserSigns");

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("DisplayIndex", "序号");
                headerDict.Add("Name", "姓名");
                headerDict.Add("CreateDate", "签到时间");
                headerDict.Add("SignImageUrl", "签到显示");

                Dictionary<string, Func<string, Tuple<Stream, ImageSettings>>> imageDict = new Dictionary<string, Func<string, Tuple<Stream, ImageSettings>>>();
                imageDict["SignImageUrl"] = (url) =>
                {
                    if (url.StartsWith("/")) url = ClientConfig.ServiceUrl + url;

                    Stream stream = Utility.Common.GetImageStream(url);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

                    ImageSettings settings = new ImageSettings();
                    settings.X = 8;
                    settings.Y = 8;
                    settings.Width = 120;
                    settings.Height = settings.Width * image.Height / image.Width;

                    if (stream == null) return null;

                    return new Tuple<Stream, ImageSettings>(stream, settings);
                };

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict, imageDict);

                System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
                dialog.DefaultExt = "xlsx";
                dialog.FileName = string.Format("会签_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                dialog.Filter = "Excel|*.xlsx";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Utility.Common.SaveFile(ms, dialog.FileName);
                    Alert("导出成功，文件路径：" + dialog.FileName);
                }
            }
        }

        void exportScoreResult(Dictionary<string, object> data)
        {
            if (data.ContainsKey("ScoreResult"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("ScoreResult");

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("Title", "评分标题");
                headerDict.Add("MinScore", "最低分");
                headerDict.Add("MaxScore", "最高分");
                headerDict.Add("AvgScore", "平均分");
                headerDict.Add("ScoreCount", "评分人数");

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict);

                using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                {
                    dialog.DefaultExt = "xlsx";
                    dialog.FileName = string.Format("会议评分结果_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                    dialog.Filter = "Excel|*.xlsx";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Utility.Common.SaveFile(ms, dialog.FileName);
                        Alert("导出成功，文件路径：" + dialog.FileName);
                    }
                }
            }
        }

        void exportVoteResult(Dictionary<string, object> data)
        {
            if (data.ContainsKey("VoteResult"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("VoteResult");

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("Title", "投票标题");
                headerDict.Add("VoteItem", "投票项");
                headerDict.Add("VoteCount", "投票数");

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict);

                using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                {
                    dialog.DefaultExt = "xlsx";
                    dialog.FileName = string.Format("会议投票结果_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                    dialog.Filter = "Excel|*.xlsx";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Utility.Common.SaveFile(ms, dialog.FileName);
                        Alert("导出成功，文件路径：" + dialog.FileName);
                    }
                }
            }
        }

        void exportUsers(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Users"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("Users");

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("DisplayIndex", "设备序号");
                headerDict.Add("UserName", "姓名");
                headerDict.Add("DeviceRole", "设备角色");

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict);

                using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                {
                    dialog.DefaultExt = "xlsx";
                    dialog.FileName = string.Format("座位布局用户_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                    dialog.Filter = "Excel|*.xlsx";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Utility.Common.SaveFile(ms, dialog.FileName);
                        Alert("导出成功，文件路径：" + dialog.FileName);
                    }
                }
            }
        }

        void exportVotes(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Votes"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("Votes");

                dictList = dictList.Where(w => w.GetStringValue("StatusName") == "已结束").ToList();
                if (dictList.Count == 0)
                {
                    this.Alert("未有已结束的投票");
                    return;
                }

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("Title", "标题");
                headerDict.Add("VoteTypeName", "投票类型");
                headerDict.Add("StatusName", "状态");
                headerDict.Add("IsChangeName", "允许修改");
                headerDict.Add("VoteItems", "投票选项");
                headerDict.Add("Remark", "投票说明");
                //headerDict.Add("IsRealNameName", "是否匿名");

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict);

                using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                {
                    dialog.DefaultExt = "xlsx";
                    dialog.FileName = string.Format("会议投票_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                    dialog.Filter = "Excel|*.xlsx";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Utility.Common.SaveFile(ms, dialog.FileName);
                        Alert("导出成功，文件路径：" + dialog.FileName);
                    }
                }
            }
        }

        void exportScores(Dictionary<string, object> data)
        {
            if (data.ContainsKey("Scores"))
            {
                List<Dictionary<string, object>> dictList = data.GetValue<List<Dictionary<string, object>>>("Scores");

                dictList = dictList.Where(w => w.GetStringValue("StatusName") == "已结束").ToList();
                if (dictList.Count == 0)
                {
                    this.Alert("未有已结束的评分");
                    return;
                }

                Dictionary<string, string> headerDict = new Dictionary<string, string>();
                headerDict.Add("Title", "标题");
                headerDict.Add("ScoreTypeName", "评分类型");
                headerDict.Add("StatusName", "状态");
                headerDict.Add("IsChangeName", "允许修改");
                headerDict.Add("Remark", "评分说明");
                //headerDict.Add("IsRealNameName", "是否匿名");

                MemoryStream ms = ExcelUtility.ExportExcel2007(dictList, headerDict);

                using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
                {
                    dialog.DefaultExt = "xlsx";
                    dialog.FileName = string.Format("会议评分_{0}.xlsx", DateTime.Now.ToString("MMddHHmmss"));
                    dialog.Filter = "Excel|*.xlsx";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Utility.Common.SaveFile(ms, dialog.FileName);
                        Alert("导出成功，文件路径：" + dialog.FileName);
                    }
                }
            }
        }

        void importTemplate()
        {
            using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择一个文件夹";
                System.Windows.Forms.DialogResult dialogResult = folderBrowserDialog.ShowDialog();

                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog.SelectedPath);

                        var dirs = directoryInfo.GetDirectories();
                        if (dirs.Length == 0)
                        {
                            this.Alert("选择的文件夹没有子文件夹！");
                            return;
                        }

                        List<Entity.UploadFile> uploadFiles = new List<Entity.UploadFile>();
                        foreach (DirectoryInfo dir in dirs)
                        {
                            getDirectoryFiles(uploadFiles, dir, "/" + dir.Name + "/", 2);
                        }

                        Dictionary<string, object> data = new Dictionary<string, object>();
                        data["Files"] = uploadFiles;
                        data["Title"] = directoryInfo.Name;

                        if (uploadFiles.Count == 0)
                        {
                            alertNoFile();
                            return;
                        }

                        _WebView2.Send("importTemplate", data);
                    }
                    catch (Exception ex)
                    {
                        Alert(ex.Message);
                    }
                }
            }
        }

        void downloadTemplate()
        {
            using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择一个文件夹";
                System.Windows.Forms.DialogResult dialogResult = folderBrowserDialog.ShowDialog();

                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    string path = folderBrowserDialog.SelectedPath + "\\会议标题1";
                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                    string path1 = path + "\\会议议题1";
                    if (!Directory.Exists(path1)) Directory.CreateDirectory(path1);

                    string path2 = path + "\\会议议题2";
                    if (!Directory.Exists(path2)) Directory.CreateDirectory(path2);

                    string pdfUrl = AppDomain.CurrentDomain.BaseDirectory + "res\\example1.pdf";
                    string wordUrl = AppDomain.CurrentDomain.BaseDirectory + "res\\example1.docx";

                    string fileName1 = path1 + "\\会议文件1.docx";
                    if (!File.Exists(fileName1))
                    {
                        if (System.IO.File.Exists(wordUrl)) File.Copy(wordUrl, fileName1);
                        else using (File.Create(fileName1)) { }
                    }

                    fileName1 = path1 + "\\会议文件2.pdf";
                    if (!File.Exists(fileName1))
                    {
                        if (System.IO.File.Exists(pdfUrl)) File.Copy(pdfUrl, fileName1);
                        else using (File.Create(fileName1)) { }
                    }

                    fileName1 = path2 + "\\会议文件3.docx";
                    if (!File.Exists(fileName1))
                    {
                        if (System.IO.File.Exists(wordUrl)) File.Copy(wordUrl, fileName1);
                        else using (File.Create(fileName1)) { }
                    }

                    fileName1 = path2 + "\\会议文件4.pdf";
                    if (!File.Exists(fileName1))
                    {
                        if (System.IO.File.Exists(pdfUrl)) File.Copy(pdfUrl, fileName1);
                        else using (File.Create(fileName1)) { }
                    }

                    Alert("下载成功，保存路径为：" + path);
                }
            }
        }

        void setFilterResponse()
        {
            _WebView2.Filters = new List<string>()
            {
                "http://*/api/VisitUser2/GetUserInfo?*"
            };

            _WebView2.SetResourceResponse = (res) => SetResourceResponse(res);
        }

        Entity.UserInfo setGetUserInfoResponse()
        {
            if (UserInfo == null)
            {
                try
                {
                    Entity.UserInfo userInfo = new Entity.UserInfo();
                    userInfo.Serial = ClientConfig.Serial;
                    UserInfo = RequestService.GetUserInfo(userInfo);
                    if (UserInfo != null)
                    {
                        UserInfo.VersionTime = GetVersionTime();
                        if (!string.IsNullOrEmpty(AppSetting.Theme)) UserInfo.Theme = AppSetting.Theme;
                        UserInfo.IsChangeService = string.IsNullOrEmpty(AppSetting.ServiceUrl);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return UserInfo;
        }

        string GetVersionTime()
        {
            string fileName = AppDomain.CurrentDomain.BaseDirectory + "version.txt";
            if (File.Exists(fileName))
            {
                return File.ReadAllText(fileName);
            }
            return string.Empty;
        }

        void SetResourceResponse(Microsoft.Web.WebView2.Core.CoreWebView2WebResourceRequestedEventArgs e)
        {
            bool isGetUserInfo = e.Request.Uri.ToLower().Contains("visituser2/getuserinfo");

            Dictionary<string, object> dict = new Dictionary<string, object>();

            string headers = "Content-Type:application/json;charset=utf-8";
            var coreWebView2 = _WebView2.GetCoreWebView2();
            try
            {
                if (isGetUserInfo)
                {
                    dict["Data"] = setGetUserInfoResponse();
                    dict["Token"] = RequestService.Token;
                    dict["Result"] = true;
                }
            }
            catch (Exception ex)
            {
                dict.Add("Message", ex.Message);
                if (!string.IsNullOrEmpty(RequestService.Token)) dict["Token"] = RequestService.Token;
                dict["Result"] = false;
                LoggerProxy.Exception("Meeting.Index", "SetResourceResponse", ex);
            }
            System.IO.MemoryStream ms = Utility.Common.StringToMemoryStream(Utility.Common.ToJson(dict));
            e.Response = coreWebView2.Environment.CreateWebResourceResponse(ms, 200, "OK", headers);
        }

        public void ReceiveStartShare(Dictionary<string, object> data)
        {
            int shareType = data.GetValue<int>("ShareType");
            if (shareType == 1 && (UserInfo.DeviceType == 1|| UserInfo.DeviceType==3)) SetStartPlay(data);
            else if (shareType == 2 && UserInfo.DeviceType == 3) SetStartPlay(data);
        }

        void receiveEndShare(bool isRece)
        {
            if (!_IsPlay)
            {
                _WebView2.Send("endReceShare");
                if (isRece) UserInfo.ReceSharingData = null;
                return;
            }
            StopPublishPlay();

            _Grid3.SetVisible(false);
            if (_DocumentViewing != null) _DocumentViewing.Grid.Visibility = Visibility.Visible;
            else if (_VideoPlay != null) _VideoPlay.SetVisible(true);
            else _Grid2.SetVisible(true);
            _Popup1.Hide();
            _EndShareFrom = true;
            if (_Form != null) _Form.Close();
            _WebView2.Send("endReceShare");
            if (isRece) UserInfo.ReceSharingData = null;
        }

        bool _EndShareFrom { get; set; }

        public void StartShare(Dictionary<string, object> data)
        {
            var isMin = data.GetValue<bool>("IsMin");
            if (isMin) this.SetFormWindowState("Minimized");
            SetStartPublish(data);
        }

        public void ShowDialogEndShare(IControl ctl)
        {
            this.Confrim("确定退出当前屏幕共享吗？", () =>
            {
                receiveEndShare(false);
            });
        }

        public Entity.UserInfo UserInfo { get; set; }

        bool isLoading { get; set; }
        public void Save(IControl ctl)
        {
            if (isLoading) return;
            Dictionary<string, object> dict = new Dictionary<string, object>();

            var meetingRoomId = (string)meetingRoomComboBox.GetValue();
            var displayIndex = (string)dispalyIndexComboBox.GetValue();

            if (!judgeNullable(meetingRoomId, "请选择会议室")) return;
            if (!judgeNullable(displayIndex, "请输入设备序号")) return;

            isLoading = true;

            Entity.UserInfo userInfo = new Entity.UserInfo();
            userInfo.Serial = ClientConfig.Serial;
            userInfo.MacAddress = ClientConfig.Mac;
            userInfo.DeviceType = int.Parse((string)deviceTypeComboBox.GetValue());
            userInfo.SystemName = "Windows";
            userInfo.DisplayIndex = int.Parse(displayIndex);
            userInfo.MeetingRoomId = meetingRoomId;

            try
            {
                userInfo = RequestService.GetUserInfo(userInfo);
                if (userInfo != null)
                {
                    UserInfo = userInfo;
                    UserInfo.VersionTime = GetVersionTime();
                    if (!string.IsNullOrEmpty(AppSetting.Theme)) UserInfo.Theme = AppSetting.Theme;
                    UserInfo.IsChangeService = string.IsNullOrEmpty(AppSetting.ServiceUrl);

                    ClientConfig.ServiceUrl = RequestService.ServeiceUrl;
                    Utility.Common.SaveConfig<Entity.ClientConfig>("clientConfig", ClientConfig);

                    _Grid1.SetVisible(false);
                    string pageName = "index";
                    if (userInfo.DeviceType == 2) pageName = "serviceList";
                    else if (userInfo.DeviceType == 3) pageName = "bigScreen";
                    _Url = GetWebUrl(pageName);
                    _WebView2.SetValue(_Url);
                    _Grid2.SetVisible(true);
                }
                else Alert("操作失败");
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }

            isLoading = false;
        }

        bool judgeNullable(string value, string message)
        {
            if (string.IsNullOrEmpty(value)) { Alert(message); return false; }
            return true;
        }

        void InitStreaming()
        {
            try
            {
                InitSmartConfig();
                StreamingMediaManager.GetCurrectWindow = () => this.Window;
                StreamingMediaManager.AlertException = (e, m, ex) => MessageBox.Show(ex.Message, "提示信息");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示信息");
                LoggerProxy.Exception(Name, "InitForm", ex);
            }
        }

        public void SendMessage(string type, Dictionary<string,object> data)
        {
            _WebView2.Send(type, data);
        }

        System.Windows.Forms.Form _Form { get; set; }

        public void SetStartPlay(Dictionary<string, object> data)
        {
            if (IsPublish) return;

            if (_IsPlay) StopPublishPlay();

            string liveUrl = data.GetStringValue("LiveUrl");
            if (string.IsNullOrEmpty(liveUrl)) return;

            string dispalyIndex = data.GetStringValue("DisplayIndex");
            shareTextButton.SetLabelText("设备" + dispalyIndex + "的屏幕共享");

            if (_DocumentViewing != null) _DocumentViewing.Grid.Visibility = Visibility.Collapsed;
            else if (_VideoPlay != null) _VideoPlay.SetVisible(false);
            else _Grid2.SetVisible(false);
            if (_Popup2.IsOpen) _Popup2.Hide();

            _Grid3.SetVisible(true);

            Task.Run(() =>
            {
                Thread.Sleep(100);

                this.Window.Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var pictureBox = new System.Windows.Forms.PictureBox();
                        pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;

                        _EndShareFrom = false;
                        _Form = new System.Windows.Forms.Form();
                        _Form.Width = Convert.ToInt32(this.Window.ActualWidth);
                        _Form.Height = Convert.ToInt32(this.Window.ActualHeight);
                        _Form.Controls.Add(pictureBox);
                        _Form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                        _Form.ShowInTaskbar = false;
                        _Form.TransparencyKey = System.Drawing.Color.Magenta;
                        _Form.AllowTransparency = true;
                        _Form.BackColor = System.Drawing.Color.Magenta;
                        _Form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                        _Form.FormClosed += _Form_FormClosed;

                        StreamingMediaManager.StartPlay(Window, pictureBox, liveUrl, setStatus);
                        _IsPlay = true;
                        UserInfo.ReceSharingData = data;
                     
                        _Form.Show();
                        _Popup1.SetPlacementTarget(Window);
                        _Popup1.Show();

                        _WebView2.Send("startReceShare");
                    }
                    catch (Exception ex)
                    {
                        _Grid3.SetVisible(false);
                        if (_DocumentViewing != null) _DocumentViewing.Grid.Visibility = Visibility.Visible;
                        else if (_VideoPlay != null) _VideoPlay.SetVisible(true);
                        else _Grid2.SetVisible(true);
                        _Popup1.Hide();
                        MessageBox.Show(ex.Message, "提示信息");
                        LoggerProxy.Exception(Name, "SetStartPlay", ex);
                        _WebView2.Send("endReceShare");
                    }
                });
            });
        }

        private void _Form_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            if (!_EndShareFrom) Window.Close();
        }

        void setStatus(string status)
        {
        }
        /// <summary>
        /// 流媒体，初始化推送
        /// </summary>
        public void SetStartPublish(Dictionary<string, object> data)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.PushUrl))
                {
                    Alert("请先设置会议室推流地址");
                    return;
                }
                if (UserInfo.PushUrl.ToLower().EndsWith("/live")) UserInfo.PushUrl += "/stream"; 
                string liveUrl = UserInfo.PushUrl.TrimEnd('/') + Guid.NewGuid().ToString().Substring(0, 8);
                StreamingMediaManager.StartPublish(this.Window, liveUrl);
                data["LiveUrl"] = liveUrl;
                data["DisplayIndex"] = UserInfo.DisplayIndex;
                _WebView2.Send("startShare", data);
                IsPublish = true;
                if (_DocumentViewing != null) _DocumentViewing.SetShareText(IsPublish);
                getShareText();
                UserInfo.SendSharingData = data;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示信息");
                LoggerProxy.Exception(Name, "SetStartPublish", ex);
            }
        }


        void InitSmartConfig()
        {
            try
            {
                StreamingMediaManager.SmartPublisherConfig = Utility.Common.DictionaryTo<SmarterStreaming.SmartPublisherConfig>(ViewConfig.GetView("SmartPublisherConfig"));
                StreamingMediaManager.SmartPlayerConfig = Utility.Common.DictionaryTo<SmarterStreaming.SmartPlayerConfig>(ViewConfig.GetView("SmartPlayerConfig"));
            }
            catch (Exception ex)
            {
                LoggerProxy.Exception(Name, "InitSmartConfig", ex);
            }

            SmarterStreaming.SmartPublisher.InitSDK();
            SmarterStreaming.SmartPlayer.InitSDK();

            StreamingMediaManager.InitConfig();
        }

        public void EndShare()
        {
            StopPublishPlay();

            _WebView2.Send("endShare");
            UserInfo.SendSharingData = null;
        }


        bool _IsPlay { get; set; }
        public bool IsPublish { get; set; }

        void StopPublishPlay()
        {
            try
            {
                if (IsPublish)
                {
                    StreamingMediaManager.StopPublish();
                    IsPublish = false;
                    if (_DocumentViewing != null) _DocumentViewing.SetShareText(IsPublish);
                    getShareText();
                }
                if (_IsPlay)
                {
                    StreamingMediaManager.StopPlay();
                    _IsPlay = false;
                }
            }
            catch (Exception ex)
            {
                LoggerProxy.Exception(Name, "StopPublishPlay", ex);
            }
        }

        void SetExit()
        {
            try
            {
                StopPublishPlay();
                SmarterStreaming.SmartPublisher.UnInitSDK();
                SmarterStreaming.SmartPlayer.UnInitSDK();
                FileReader2.Dispose();
                //CreateFile.Dispose();
                CreateRecord.Dispose();
                InkCanvasTab.Dispose();
                Controls.VlcPlayer.Dispose();
                if (_SecondIndex != null)
                {
                    _SecondIndex.Window.Close();
                    _SecondIndex = null;
                }
                if (_MeetingNotice != null)
                {
                    _MeetingNotice.Close();
                    _MeetingNotice = null;
                }
            }
            catch (Exception ex)
            {
                LoggerProxy.Exception(Name, "SetExit", ex);
            }
        }

        public void DocumnetViewingToBack()
        {
            _DocumentViewing.Grid.Visibility = Visibility.Collapsed;
            this._Grid2.SetVisible(true);
            if (_DocumentViewing.TabList.Count > 0) _Popup2.Show();
        }

        public void ShowDocumentView()
        {
            _Grid2.SetVisible(false);
            _DocumentViewing.Grid.Visibility = Visibility.Visible;
            _Popup2.Hide();
        }

        VideoPlay _VideoPlay { get; set; }

        public void VideoPlayToBack()
        {
            _VideoPlay.SetVisible(false);
            this.Grid.Children.Remove(_VideoPlay.Grid);
            this._Grid2.SetVisible(true);
            _VideoPlay = null;
        }
    }
}
